package com.sunbim.rsrv.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunbim.rsrv.common.exception.RequestException;
import com.sunbim.rsrv.mapper.RelicsMapper;
import com.sunbim.rsrv.mapper.RiskAroundMapper;
import com.sunbim.rsrv.pojo.RiskAround;
import com.sunbim.rsrv.service.RiskAroundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 周边环境风险 服务实现类
 * </p>
 *
 * @author yuhui
 * @since 2021-12-30
 */
@Service
public class RiskAroundServiceImpl extends ServiceImpl<RiskAroundMapper, RiskAround> implements RiskAroundService {
    @Autowired
    RiskAroundMapper riskAroundMapper;

    @Autowired
    RelicsMapper relicsMapper;

    @Override
    public RiskAround selectByRelicsId(Integer userId, Integer relicsId) {
        // 根据文物ID查询数据
        QueryWrapper<RiskAround> wrapper = new QueryWrapper<>();
        wrapper.eq("relics_id", relicsId);
        RiskAround riskAround = riskAroundMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(riskAround)) throw new RequestException("文物id: " + relicsId + " 的风险数据不存在");

        int level = getLevel(riskAround.getScore());
        riskAround.setLevel(level);
        return riskAround;
    }

    /**
     * 计算周边风险等级
     * 一级：得分0-1分
     * 二级：得分2-4分
     * 三级：得分5-7分
     * 四级：得分8-9分
     */
    public static int getLevel(Integer score) {
        int level;
        if (score == null || score <= 1) level = 1;
        else if (score <= 4) level = 2;
        else if (score <= 7) level = 3;
        else level = 4;
        return level;
    }

    @Override
    public void updateByRiskId(RiskAround params) {
        boolean isIdExist = riskAroundMapper.idExist(params.getId());
        if (!isIdExist) throw new RequestException("风险id: " + params.getId() + " 不存在");

        int score = params.getAround();
        params.setScore(score);
        riskAroundMapper.updateById(params);
    }

    public List<RiskAround> getAllByUserId(Integer userId) {
        QueryWrapper<RiskAround> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return riskAroundMapper.selectList(wrapper);
    }
}
